#import "LoginController.h"
#import "SettingViewController.h"
#import "UIImage.h"
#import <Masonry/Masonry.h>
#import <AFNetworking/AFNetworking.h>
#import "UserData.h"
#import "TabBarController.h"
@interface LoginController ()
@property(nonatomic,strong)UITextField* Account;
@property(nonatomic,strong)UITextField* Password;
@property(nonatomic,strong)UIButton* loginButton;
@property(nonatomic,strong)UIButton* signupButton;
@property(nonatomic,strong)UIButton* signupButton2;
@property(nonatomic,strong)UIButton* signupButton3;
@property(nonatomic,strong)UITextField* SUAcount;
@property(nonatomic,strong)UITextField* SUPassword;
@property(nonatomic,strong)UITextField* SUName;
@property(nonatomic, strong) UIWindow* window;
@end

@implementation LoginController

- (void)viewDidLoad {
    [super viewDidLoad];
        [self.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"testAvator1.jpg"]]];
        _SUName =[[UITextField alloc]initWithFrame:CGRectMake(20,140,self.view.frame.size.width-40,50)];
        _SUName.backgroundColor = [UIColor clearColor];
        _SUName.placeholder = [NSString stringWithFormat:@" Name"];
        [_SUName setHidden:YES];
        _SUName.layer.borderWidth = 1.5f;//边框大小
        _SUName.layer.cornerRadius = 5;//边框圆角大小//设置占位字的颜色
        _SUName.layer.borderColor = [UIColor whiteColor].CGColor;//边框颜色
        [self.view addSubview:_SUName];
    

        
        _Account=[[UITextField alloc]initWithFrame:CGRectMake(20,200,self.view.frame.size.width-40,50)];
        _Account.backgroundColor=[UIColor clearColor];
        _Account.placeholder= [NSString stringWithFormat:@" Email"];
        _Account.layer.borderWidth = 1.5f;//边框大小
        _Account.layer.cornerRadius = 5;//边框圆角大小//设置占位字的颜色
        _Account.layer.borderColor = [UIColor whiteColor].CGColor;//边框颜色
        [self.view addSubview:_Account];
        
        _SUAcount =[[UITextField alloc]initWithFrame:CGRectMake(20,200,self.view.frame.size.width-40,50)];
        _SUAcount.backgroundColor = [UIColor clearColor];
        _SUAcount.placeholder = [NSString stringWithFormat:@" Email"];
        [_SUAcount setHidden:YES];
        _SUAcount.layer.borderWidth = 1.5f;//边框大小
        _SUAcount.layer.cornerRadius = 5;//边框圆角大小//设置占位字的颜色
        _SUAcount.layer.borderColor = [UIColor whiteColor].CGColor;//边框颜色
        [self.view addSubview:_SUAcount];
        
        _Password = [[UITextField alloc]initWithFrame:CGRectMake(20,260,self.view.frame.size.width-40,50)];
        _Password.backgroundColor=[UIColor clearColor];
        _Password.placeholder=[NSString stringWithFormat:@" Password"];
        [_Password setSecureTextEntry:YES];
        _Password.layer.borderWidth = 1.5f;//边框大小
        _Password.layer.cornerRadius = 5;//边框圆角大小//设置占位字的颜色
        _Password.layer.borderColor = [UIColor whiteColor].CGColor;//边框颜色
        [self.view addSubview:_Password];
        
        _SUPassword = [[UITextField alloc]initWithFrame:CGRectMake(20,260,self.view.frame.size.width-40,50)];
        _SUPassword.backgroundColor = [UIColor clearColor];
        _SUPassword.placeholder = [NSString stringWithFormat:@" Password"];
        [_SUPassword setSecureTextEntry:YES];
        [_SUPassword setHidden:YES];
        _SUPassword.layer.borderWidth = 1.5f;//边框大小
        _SUPassword.layer.cornerRadius = 5;//边框圆角大小//设置占位字的颜色
        _SUPassword.layer.borderColor = [UIColor whiteColor].CGColor;//边框颜色
        [self.view addSubview:_SUPassword];
        
        _loginButton=[UIButton buttonWithType:UIButtonTypeRoundedRect];
        [_loginButton setFrame:CGRectMake(20,320,self.view.frame.size.width-40,50)];
        [_loginButton setTitle:@"Login"forState:UIControlStateNormal];
        [_loginButton setBackgroundColor:[UIColor colorWithRed:51/255.0 green:102/255.0 blue:255/255.0 alpha:1]];
        [_loginButton setTitleColor:[UIColor whiteColor]forState:UIControlStateNormal];
        [_loginButton addTarget:self
                         action:@selector(Loginbutton:) forControlEvents:UIControlEventTouchUpInside];
        _loginButton.layer.masksToBounds = YES; //允许绘制

        _loginButton.layer.cornerRadius = 4;//边框弧度

        _loginButton.layer.borderWidth = 1; //边框的宽度
    
        [self.view addSubview:_loginButton];
        
        _signupButton=[UIButton buttonWithType:UIButtonTypeRoundedRect];
        [_signupButton setFrame:CGRectMake(20,380,self.view.frame.size.width-40,50)];
        [_signupButton setTitle:@"SignUp" forState:UIControlStateNormal];
        [_signupButton setBackgroundColor:[UIColor colorWithRed:51/255.0 green:102/255.0 blue:255/255.0 alpha:1]];
        [_signupButton setTitleColor:[UIColor whiteColor]forState:UIControlStateNormal];
        [_signupButton addTarget:self
                          action:@selector(SignUP:) forControlEvents:UIControlEventTouchUpInside];
        _signupButton.layer.masksToBounds = YES; //允许绘制

        _signupButton.layer.cornerRadius = 4;//边框弧度

        _signupButton.layer.borderWidth = 1; //边框的宽度
        [self.view addSubview:_signupButton];
        
        _signupButton2=[UIButton buttonWithType:UIButtonTypeRoundedRect];
        [_signupButton2 setFrame:CGRectMake(20,440,self.view.frame.size.width-40,50)];
        [_signupButton2 setTitle:@"Finish" forState:UIControlStateNormal];
        [_signupButton2 setBackgroundColor:[UIColor colorWithRed:51/255.0 green:102/255.0 blue:255/255.0 alpha:1]];
        [_signupButton2 setTitleColor:[UIColor whiteColor]forState:UIControlStateNormal];
        [_signupButton2 addTarget:self
                          action:@selector(SignUP2:) forControlEvents:UIControlEventTouchUpInside];
        [_signupButton2 setHidden:YES];
        _signupButton2.layer.masksToBounds = YES; //允许绘制

        _signupButton2.layer.cornerRadius = 4;//边框弧度

        _signupButton2.layer.borderWidth = 1; //边框的宽度
        [self.view addSubview:_signupButton2];
    
        _signupButton3=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    [_signupButton3 setFrame:CGRectMake(20,500,self.view.frame.size.width-40,50)];
    [_signupButton3 setTitle:@"Back" forState:UIControlStateNormal];
    [_signupButton3 setBackgroundColor:[UIColor colorWithRed:51/255.0 green:102/255.0 blue:255/255.0 alpha:1]];
    [_signupButton3 setTitleColor:[UIColor whiteColor]forState:UIControlStateNormal];
    [_signupButton3 addTarget:self
                      action:@selector(SignUP3:) forControlEvents:UIControlEventTouchUpInside];
    [_signupButton3 setHidden:YES];
    _signupButton3.layer.masksToBounds = YES; //允许绘制

    _signupButton3.layer.cornerRadius = 4;//边框弧度

    _signupButton3.layer.borderWidth = 1; //边框的宽度
    [self.view addSubview:_signupButton3];
}




    - (void)gotoMain{
        self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
        UITabBarController *tabBarVC = [[UITabBarController alloc] init];
        
    }

    - (void)Loginbutton:(UIButton*)button{
        NSString* email = [_Account text];
        NSString* pwd = [_Password text];
        [self  logInWithEmail:email AndPassword:pwd];
    }

    - (void)SignUP:(UIButton*)buttonView{
        [_Account setHidden:YES];
        [_Password setHidden:YES];
        [_SUName setHidden:NO];
        [_SUAcount setHidden:NO];
        [_SUPassword setHidden:NO];
        [_signupButton2 setHidden:NO];
        [_signupButton3 setHidden:NO];
    }

    - (void)SignUP2:(UIButton*)buttonView{
        NSString* email = [_SUAcount text];
        NSString* pwd = [_SUPassword text];
        NSString* name = [_SUName text];
        [self signUpWithUsername:name andEmail:email andPassword:pwd];
    }

    - (void)SignUP3:(UIButton*)buttonView{
        [_Account setHidden:NO];
        [_Password setHidden:NO];
        [_SUName setHidden:YES];
        [_SUAcount setHidden:YES];
        [_SUPassword setHidden:YES];
        [_signupButton2 setHidden:YES];
        [_signupButton3 setHidden:YES];
    }


    - (void)logInWithEmail:(NSString *)email
               AndPassword:(NSString *)password
    {
     NSString *URL = @"http://172.18.178.56/api/user/login/pass";
        NSDictionary *body = @{
            @"name":email,
            @"password":password
        };
        
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.requestSerializer = [AFJSONRequestSerializer serializer];
        manager.responseSerializer = [AFJSONResponseSerializer serializer];
        
        [manager POST:URL parameters:body headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSLog(@"\nRequest success with responce %@", responseObject);
            NSDictionary *response = (NSDictionary *)responseObject;
            
            // 如果登录成功
            if([[response valueForKey:@"State"] isEqualToString:@"success"])
            {
                NSLog(@"LogIn success");
                
                // 获取个人信息
                //__block NSDictionary *selfInfo = nil;
                NSString *selfURL = @"http://172.18.178.56/api/user/info/self";
                [manager GET:selfURL parameters:nil headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                    NSLog(@"\nSelf Info: %@", responseObject);
                    NSDictionary *selfInfo = (NSDictionary *)responseObject;
                    
                    [UserInfo configUser:selfInfo];
                    [UserData LoadUser:selfInfo];
                    // 找到主界面，更改根vc
                    UIWindow* window = nil;
                    if (@available(iOS 13.0, *))
                    {
                        for (UIWindowScene* windowScene in [UIApplication sharedApplication].connectedScenes)
                            if (windowScene.activationState == UISceneActivationStateForegroundActive)
                            {
                                window = windowScene.windows.firstObject;
                                break;
                            }
                    }
                    else
                    {
                        window = [UIApplication sharedApplication].keyWindow;
                    }
                    window.rootViewController = [[TabBarController alloc]init];
                    
                } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                    NSLog(@"Get self info failed somehow");
                }];
            }
            else if([[response valueForKey:@"Data"] isEqualToString:@"not found"])
            {
                [self Alert:@"没有这个账号"];
            }
            else if([[response valueForKey:@"Data"] isEqualToString:@"crypto/bcrypt: hashedPassword is not the hash of the given password"])
            {
                [self Alert:@"密码错误"];
            }

        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            // 请求失败
            NSLog(@"request failure");
        }];
        
        
    }


    - (void)signUpWithUsername:(NSString *)username
                      andEmail:(NSString *)email
                   andPassword:(NSString *)password
    {
        NSString *URL = @"http://172.18.178.56/api/user/register";
        NSDictionary *body = @{
            @"name":username,
            @"password":password,
            @"email":email
        };
        
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.requestSerializer = [AFJSONRequestSerializer serializer];
        manager.responseSerializer = [AFJSONResponseSerializer serializer];
        
        [manager POST:URL parameters:body headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSLog(@"%@",responseObject);
            NSDictionary *response = (NSDictionary *)responseObject;
            if([response[@"State"] isEqualToString:@"success"])
            {
                [self Alert:@"注册成功"];
                [self.Account setText:email];
                [self.Password setText:password];
                [self.Account setHidden:NO];
                [self.Password setHidden:NO];
                [self.SUName setHidden:YES];
                [self.SUAcount setHidden:YES];
                [self.SUPassword setHidden:YES];
                [self.signupButton2 setHidden:YES];
            }
            else
            {
                [self Alert:@"注册失败"];
            }
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            // 请求失败
            NSLog(@"request failure");
        }];
    }

    - (void)Alert:(NSString *)msg
    {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示"
                                                                       message:msg
                                                                preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
        
        // 显示对话框
        [self presentViewController:alert animated:true completion:nil];
    }


@end
